package com.cspg.design.http;


import com.cspg.design.BuildConfig;
import com.cspg.design.bean.UserInfo;
import com.cspg.design.common.Constant;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Authenticator;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;

/**
 * Created by Kun Chan on 2017/4/17.
 */

public class RetrofitUtil {
    public static final int DEFAULT_TIMEOUT = 3000;

    public Retrofit mRetrofit;

    private boolean isFirst = true;

    public RetrofitUtil() {

        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        Interceptor mAuthenticatorInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                // 获取请求
                Request request = chain.request();
                // 获取响应
                Response response = chain.proceed(request);
                // 在这里判断是不是是token失效
                // 当然，判断条件不会这么简单，会有更多的判断条件的
                if (response.code() == 401) {
                    // 这里应该调用自己的刷新token的接口
                    // 这里发起的请求是同步的，刷新完成token后再增加到header中
                    // 这里抛出的错误会直接回调 onError
//                String token = refreshToken();
//                    String token = UserInfo.getInstance().token;
//                    // 创建新的请求，并增加header
//                    Request retryRequest = chain.request()
//                            .newBuilder()
//                            .header("Authorization", token)
//                            .build();
                    return null;
                    // 再次发起请求
//                    return chain.proceed(retryRequest);
                }

                return response;
            }
        };
        if (BuildConfig.DEBUG) {
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        }

        //可以利用okhttp实现缓存
        OkHttpClient client = new OkHttpClient.Builder()
                .retryOnConnectionFailure(true)//连接失败后是否重新连接
                .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .authenticator(authorization)
//                .addInterceptor(mAuthenticatorInterceptor)
                .addInterceptor(logging)
                .followRedirects(false)
                .followSslRedirects(false)
                .build();

        //创建retrofit对象
        mRetrofit = new Retrofit.Builder()
                .client(client)
                .baseUrl(Constant.HOST)
                .addConverterFactory(FastJsonConverterFactory.create())//在此处声明使用FastJsonConverter做为转换器
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
    }

    private Authenticator authorization = new Authenticator() {
        @Override
        public Request authenticate(Route route, Response response) throws IOException {
            //-----------核心代码-------
            // 这里抛出的错误会直接回调 onError
            // 这里发起的请求是同步的，刷新完成token后再增加到header中
            // String token = refreshToken();
            if (response.code() == 401 && isFirst) {
                // 这里应该调用自己的刷新token的接口
                // 这里发起的请求是同步的，刷新完成token后再增加到header中
                // 这里抛出的错误会直接回调 onError
//                EventBus.getDefault().post(LoginEvent.getInstance(true));
                isFirst = false;
                String token = "";
                if (token == null)
                {
                    return null;
                }
                return response.request()
                        .newBuilder()
                        .header("Authorization", token)
                        .build();
            }
            else
            {
                return  null;
            }
        }
    };

    public <T> T createReq(Class<T> reqServer) {
        return mRetrofit.create(reqServer);
    }

}
